package com.dmsdbj.itoo.graduate.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dmsdbj.itoo.graduate.entity.PersonalInfoEntity;
import com.dmsdbj.itoo.graduate.entity.ext.*;
import com.dmsdbj.itoo.graduate.facade.PersonalInfoFacade;
import com.dmsdbj.itoo.graduate.tool.ResultCode;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageInfo;
import com.sun.faces.action.*;
import io.swagger.annotations.*;
import org.jplus.hyberbin.excel.utils.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;


/**
 * @author : sxm
 * DESCRIPTION: graduate展示
 * create: 2017-11-16 14:31:07.
 */
@Api(value = "个人信息API", tags = "毕业生信息API")
@RequestMapping("/personalInfo")
@Controller
public class PersonalInfoController {

    //定义打印日志相关
    private static final Logger logger = LoggerFactory.getLogger(PersonalInfoController.class);

    @Reference
    private PersonalInfoFacade personalInfoFacade;
    private static final String url = "classpath:fast_client.conf";
    private static final String fileNameStart = "";


    @RequestMapping(value = {"/index"}, method = RequestMethod.GET)
    public String index() {
        return "personalInfo";
    }

    /**
     * 根据id查找毕业生-徐玲博-2017-12-4 15:46:41
     *
     * @param id 毕业生id
     */
    @ApiOperation(value = "根据id查找毕业生", notes = "根据id查找毕业生")
    @ResponseBody
    @RequestMapping(value = {"/findByUserId/{id}"}, method = RequestMethod.GET)
    public ItooResult findByUserId(@PathVariable String id) {
        try {
            PersonalInfoEntity personalInfoEntity = personalInfoFacade.findByUserId(id);
            if (personalInfoEntity != null) {
                return ItooResult.build(ResultCode.SUCCESS, "根据id查找毕业生成功", personalInfoEntity);
            } else {
                return ItooResult.build(ResultCode.SUCCESS, "根据id查找毕业生为空");
            }

        } catch (Exception e) {
            logger.error("根据id查找毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "根据id查找毕业生失败");
        }
    }

    /**
     * 根据id 查询个人信息-包括图像-徐玲博-2018-2-6 15:35:22
     *
     * @param id 用户id
     * @return 用户信息
     */
    @ApiOperation(value = "根据id 查询个人信息-包括图像", notes = "根据id 查询个人信息-包括图像")
    @ResponseBody
    @RequestMapping(value = "selectByPersonId/{id}", method = RequestMethod.GET)
    public ItooResult selectByPersonId(@PathVariable String id) {
        try {
            PersonInfoModel personInfoModel = personalInfoFacade.selectByPersonId(id);
            if (personInfoModel != null) {
                return ItooResult.build(ResultCode.SUCCESS, "根据id查找毕业生成功", personInfoModel);
            } else {
                return ItooResult.build(ResultCode.FAIL, "根据id查找毕业生为空");
            }
        } catch (Exception e) {
            logger.error("根据id查找毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "根据id查找毕业生失败");
        }
    }

    /**
     * 毕业生-根据毕业生用户Id-添加个人信息-徐玲博-2017-11-19 11:28:07
     *
     * @param personalInfoEntity 个人信息实体
     * @return 受影响行
     */
    @ApiOperation(value = "根据毕业生用户Id-添加个人信息", notes = "根据毕业生用户Id-添加个人信息")
    @ResponseBody
    @RequestMapping(value = "addPersonInfo/", method = RequestMethod.POST)
    public ItooResult addPersonInfo(@RequestBody PersonalInfoEntity personalInfoEntity) {

        int result;
        try {
            result = personalInfoFacade.addPersonInfo(personalInfoEntity);
            if (result > 0) {
                return ItooResult.build(ResultCode.SUCCESS, "添加毕业生成功！", result);
            } else if (result==-1){
                return ItooResult.build(ResultCode.FAIL,"用户名重复！请重新输入");
            }
            else {
                return ItooResult.build(ResultCode.FAIL, "根据毕业生用户Id添加个人信息失败！");
            }
        } catch (Exception e) {
            logger.error("addPersonInfo 添加毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "添加毕业生异常！");
        }

    }

    /**
     * 根据登录ID查询用户信息-徐玲博-2017-11-19 11:32:48
     *
     * @param loginId 登录ID
     * @return 个人信息实体
     */
    @ApiOperation(value = "根据登录ID查询用户信息", notes = "根据登录ID查询用户信息")
    @ResponseBody
    @RequestMapping(value = "selectPersonByLoginId/{loginId}", method = RequestMethod.GET)
    public ItooResult selectPersonByLoginId(@PathVariable String loginId) {

        PersonalInfoEntity personalInfoEntity;
        try {
            personalInfoEntity = personalInfoFacade.selectPersonByLoginId(loginId);
            if (personalInfoEntity != null) {
                return ItooResult.build(ResultCode.SUCCESS, "添加毕业生成功", personalInfoEntity);
            } else {
                return ItooResult.build(ResultCode.FAIL, "添加毕业生失败！");
            }
        } catch (Exception e) {
            logger.error("selectPersonByLoginId 查询毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "添加毕业生失败！");
        }


    }

    /**
     * 毕业生-根据毕业生 用户Id-修改个人信息-徐玲博-2017-11-19 11:28:07
     *
     * @param personInfoModel 用户实体
     * @return 受影响行
     */
    @ApiOperation(value = "根据毕业生 用户Id-修改个人信息", notes = "根据毕业生 用户Id-修改个人信息")
    @ResponseBody
    @RequestMapping(value = "updatePersonInfo/", method = RequestMethod.POST)
    public ItooResult updatePersonInfo(@RequestBody PersonInfoModel personInfoModel) {

        int result;
        try {
            result = personalInfoFacade.updatePersonInfo(personInfoModel);
            if (result > 0) {
                return ItooResult.build(ResultCode.SUCCESS, "修改毕业生成功！", result);
            } else {
                return ItooResult.build(ResultCode.FAIL, "修改毕业生失败！");
            }
        } catch (Exception e) {
            logger.error("updatePersonInfo 毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "修改毕业生异常！");
        }

    }

    /**
     * 毕业生-根据用户Id-删除个人信息-徐玲博-2017-11-19 11:43:50
     * 删除该用户，所有相关的信息，例如家庭、公司、薪资、学历等都将被删除
     *
     * @param id       用户ID
     * @param operator 操作人
     * @return 影响行数
     */
    @ApiOperation(value = "毕业生-根据用户Id-删除个人信息", notes = "毕业生-根据用户Id-删除个人信息")
    @ResponseBody
    @RequestMapping(value = "deletePersonInfo/{id}/{operator}", method = RequestMethod.POST)
    public ItooResult deletePersonInfo(@PathVariable String id, @PathVariable String operator) {

        try {
            boolean result = personalInfoFacade.deletePersonInfo(id, operator);
            if (result) {
                return ItooResult.build(ResultCode.SUCCESS, "删除毕业生成功");
            } else {
                return ItooResult.build(ResultCode.FAIL, "删除毕业生失败！");
            }
        } catch (Exception e) {
            logger.error("deletePersonInfo 删除毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "删除毕业生异常！");
        }

    }

    /**
     * 根据毕业生姓名查询个人信息-徐玲博-2017-12-4 08:40:24
     *
     * @param name 毕业生姓名
     * @return list列表
     */
    @ApiOperation(value = "根据毕业生姓名查询个人信息", notes = "根据毕业生姓名查询个人信息")
    @ResponseBody
    @RequestMapping(value = "selectPersonByName/{name}", method = RequestMethod.GET)
    public ItooResult selectPersonByName(@PathVariable String name) {

        List<PersonalInfoEntity> personalInfoEntityList;
        try {
            personalInfoEntityList = personalInfoFacade.selectPersonByName(name);
            if (personalInfoEntityList != null) {
                return ItooResult.build(ResultCode.SUCCESS, "查询毕业生成功", personalInfoEntityList);
            } else {
                return ItooResult.build(ResultCode.FAIL, "查询毕业生失败");
            }
        } catch (Exception e) {
            logger.error("selectPersonByName查询毕业生异常", e);
            return ItooResult.build(ResultCode.FAIL, "查询毕业生失败");
        }

    }

    /**
     * 通知-查询毕业生信息-徐玲博-2017-12-6 11:55:36
     *
     * @return ItooResult及毕业生信息列表
     */
    @ApiOperation(value = "通知接口-查询毕业生信息", notes = "通知接口-查询毕业生信息")
    @ResponseBody
    @RequestMapping(value = "selectPersonInfo", method = RequestMethod.GET)
    public ItooResult selectPersonInfo() {

        List<PersonGradeModel> personalInfoEntityList;
        try {
            personalInfoEntityList = personalInfoFacade.selectPersonInfo();
            if (personalInfoEntityList != null) {
                return ItooResult.build("0000", "查询个人信息成功", personalInfoEntityList);
            } else {
                return ItooResult.build("1111", "查询个人信息失败");
            }
        } catch (Exception e) {
            logger.error("查询全部毕业生信息", e);
            return ItooResult.build("1111", "查询全部毕业生信息异常");
        }
    }

    /**
     * 根据期数查询毕业生 -李爽-2017-12-7 21:50:28
     *
     * @param grade 期数
     * @return 毕业生list
     */
    @ApiOperation(value = "根据期数查询毕业生", notes = "根据期数查询毕业生")
    @ResponseBody
    @RequestMapping(value = "selectPersonByGrade/{grade}", method = RequestMethod.GET)
    ItooResult selectPersonByGrade(@PathVariable String grade) {
        if (grade == null || "".equals(grade)) {
            return ItooResult.build(ResultCode.FAIL, "期数为空，请检查");
        }
        try {
            List<PersonalInfoEntity> list = personalInfoFacade.selectPersonByGrade(grade);
            if (!CollectionUtils.isEmpty(list)) {
                return ItooResult.build(ResultCode.SUCCESS, "根据期数查询毕业生成功", list);
            }
            return ItooResult.build(ResultCode.SUCCESS, "根据期数查询毕业生为空");
        } catch (Exception e) {
            logger.error("根据期数查询毕业生失败", e);
            return ItooResult.build(ResultCode.FAIL, "根据期数查询毕业生失败");
        }
    }

    /**
     * 模糊查询（姓名or性别or期数） - 李爽-2017-12-7 21:50:24
     *
     * @param queryParam 模糊查询条件
     * @return 毕业生list
     */
    @ApiOperation(value = "模糊查询（姓名or性别or期数）", notes = "模糊查询（姓名or性别or期数）")
    @ResponseBody
    @RequestMapping(value = "selectPersonByNameSexGrade/{queryParam}", method = RequestMethod.GET)
    ItooResult selectPersonByNameSexGrade(@PathVariable String queryParam) {
        if (queryParam == null || "".equals(queryParam)) {
            return ItooResult.build(ResultCode.FAIL, "查询内容为空，请检查");
        }
        try {
            List<PersonalInfoEntity> list = personalInfoFacade.selectPersonByNameSexGrade(queryParam);
            if (!CollectionUtils.isEmpty(list)) {
                return ItooResult.build(ResultCode.SUCCESS, "根据（姓名or性别or期数）模糊查询毕业生成功", list);
            }
            return ItooResult.build(ResultCode.SUCCESS, "根据（姓名or性别or期数）模糊查询毕业生为空");
        } catch (Exception e) {
            logger.error("根据（姓名or性别or期数）模糊查询毕业生失败", e);
            return ItooResult.build(ResultCode.FAIL, "根据（姓名or性别or期数）模糊查询毕业生失败");
        }
    }

    /**
     * 组合查询+模糊查询+分页查询 毕业生信息查询-徐玲博-2018-1-6 15:46:52
     *
     * @param name        姓名
     * @param company     公司
     * @param grade       期数
     * @param education   教育
     * @param salaryRange 薪资范围
     * @return 毕业生信息
     */
    @ApiOperation(value = "毕业生信息查询", notes = "毕业生信息查询")
    @ResponseBody
    @RequestMapping(value = "selectPersonByCombination/{name}/{company}/{grade}/{education}/{salaryRange}/{page}/{pageSize}", method = RequestMethod.GET)
    public ItooResult selectPersonByCombination(@PathVariable String name, @PathVariable String company,
                                                @PathVariable String grade, @PathVariable String education,
                                                @PathVariable String salaryRange, @PathVariable int page,
                                                @PathVariable int pageSize, HttpServletRequest request) {
        try {
            PageInfo<PersonManageModel> manageModelPageInfo = personalInfoFacade.selectPersonByCombination(name, company, grade, education, salaryRange, page, pageSize);
            if (CollectionUtils.isEmpty(manageModelPageInfo.getList())) {
                return ItooResult.build(ResultCode.FAIL, "无相关条件的查询结果！");
            }
            return ItooResult.build(ResultCode.SUCCESS, "根据相关条件查询到数据！", manageModelPageInfo);
        } catch (Exception e) {
            logger.debug(" SelectPersonByCombination is error!");
            return ItooResult.build(ResultCode.FAIL, "查询失败！");
        }
    }

    /**
     * 分页查询-根据地域类型、地域、期数、姓名、性别，查询学员信息-李爽-2018-1-13 17:27:42
     *
     * @return 学员信息
     */
    @ApiOperation(value = "地域分页查询毕业生信息", notes = "地域分页查询毕业生信息")
    @ResponseBody
    @RequestMapping(value = "selectPersonInfoByRegionGradeNameSex/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public ItooResult selectPersonInfoByRegionGradeNameSex(
            @RequestBody PersonInfoParamsModel personInfoParamsModel,
            @PathVariable int pageNum, @PathVariable int pageSize) {
        try {
            PageInfo<PersonInfoModel> pageInfo = personalInfoFacade.selectPersonInfoByRegionGradeNameSex(personInfoParamsModel, pageNum, pageSize);
            if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getList())) {
                return ItooResult.build(ResultCode.FAIL, "查询学员信息失败");
            }
            return ItooResult.build(ResultCode.SUCCESS, "分页查询-根据地域类型、地域、期数、姓名、性别，查询学员信息成功", pageInfo);
        } catch (Exception e) {
            logger.error("查询学员信息异常", e);
            return ItooResult.build(ResultCode.FAIL, "查询学员信息失败");
        }
    }


    /**
     * 数据中心-添加在校生或毕业生信息列表到到Personal表中--徐玲博-2018-1-27 15:23:00
     *
     * @param personalInfoEntityList 个人信息实体list
     * @return 受影响行
     */
    @ApiOperation(value = "添加在校生或毕业生信息列表", notes = "添加在校生或毕业生信息列表")
    @ResponseBody
    @RequestMapping(value = "addListToPersonal", method = RequestMethod.POST)
    public ItooResult addListToPersonal(@RequestBody List<PersonGradeModel> personalInfoEntityList) {
        int flag;//影响行
        try {
//            flag = personalInfoFacade.addListToPersonal(personalInfoEntityList);//通过导入学员信息
            flag = 0;  //暂时赋值，待删除
            if (personalInfoEntityList.size() == flag) {
                return ItooResult.build(ResultCode.SUCCESS, "添加学员信息成功", flag);
            } else {
                return ItooResult.build(ResultCode.FAIL, "添加学员信息失败");
            }

        } catch (Exception e) {
            logger.error("添加学员信息异常", e);
            return ItooResult.build(ResultCode.FAIL, "添加学员信息异常");
        }
    }

    /**
     * 批量添加人员信息-徐玲博-2018-1-27 15:34:23
     *
     * @return ItooResult
     */
    @ApiOperation(value = "批量添加人员信息", notes = "批量添加人员信息")
    @ResponseBody
    @RequestMapping(value = "/insertPersonInfoList", method = RequestMethod.POST)
    public ItooResult insertPersonInfoList(@RequestBody List<PersonalInfoEntity> personalInfoEntityList) {
        int flag;
        try {
            flag = personalInfoFacade.insertPersonInfoList(personalInfoEntityList);
            if (flag > 0) {
                return ItooResult.build(ResultCode.SUCCESS, "批量添加人员信息成功", flag);
            } else {
                return ItooResult.build(ResultCode.FAIL, "批量添加人员信息为空");
            }
        } catch (Exception e) {
            logger.error("批量添加人员信息异常", e);
            return ItooResult.build(ResultCode.FAIL, "批量添加人员信息失败");
        }
    }

    /**
     * 组合查询人员地域信息-徐玲博-2018-1-31 16:52:28
     *
     * @param name                人员名称
     * @param sex                 性别
     * @param regionName          地域 省市县
     * @param grade               期数
     * @param dictionaryAddressId 地域类型id
     * @return 人员地域信息列表
     */
    @ApiOperation(value = "组合查询人员地域信息", notes = "组合查询人员地域信息")
    @ResponseBody
    @RequestMapping(value = "selectPersonRegion/{name}/{sex}/{regionName}/{grade}/{dictionaryAddressId}", method = RequestMethod.GET)
    public ItooResult selectPersonRegion(@PathVariable String name, @PathVariable String sex, @PathVariable String regionName, @PathVariable String grade, @PathVariable String dictionaryAddressId) {
        List<PersonReginModel> personReginModelList;
        try {
            personReginModelList = personalInfoFacade.selectPersonRegion(name, sex, regionName, grade, dictionaryAddressId);
            if (!CollectionUtils.isEmpty(personReginModelList)) {
                return ItooResult.build(ResultCode.SUCCESS, "查询人员地域信息成功", personReginModelList);
            } else {
                return ItooResult.build(ResultCode.FAIL, "查询人员地域信息为空");
            }
        } catch (Exception e) {
            logger.error("查询人员地域信息异常", e);
            return ItooResult.build(ResultCode.FAIL, "查询人员地域信息失败");
        }
    }

    /**
     * 导出Excel模板-徐玲博-2018-2-24 10:14:34
     * @param request
     * @param response
     * @return Excel模板
     */
    @ResponseBody
    @RequestMapping(value = {"/exportExcel"}, method = RequestMethod.GET)
    public ItooResult exportExcel(HttpServletRequest request, HttpServletResponse response) {
        List<PersonGradeModel> personGradeModelList = new ArrayList<>();
        PersonGradeModel personalInfo = new PersonGradeModel();
        personalInfo.setLoginId("");
        personalInfo.setName("");
        personalInfo.setGradeName("");//期数
        personalInfo.setSex("");
        personalInfo.setWechat("");
        personalInfo.setQq("");
        personalInfo.setEmail("");
        personalInfo.setPhone("");
        personalInfo.setIsGraduateName("");//是否毕业
//        personalInfo.setBirthday();
        personGradeModelList.add(personalInfo);
        try {
            Map<Serializable, Serializable> map = new HashMap<>();
            map.put("sheetName", "互助网模板");
//
            map.put("columns", new String[]{"loginId" ,"name","gradeName","sex","isGraduateName","email","phone","wechat","qq"});
            map.put("title", "互助网模板");
            map.put("dataList", (Serializable) personGradeModelList);
            ExcelUtil.exportExcel(map, response);
            return ItooResult.build("0000", "下载成功");
        } catch (Exception e) {
            logger.error("graduateHelp-exportExecl", e);
            return ItooResult.build("1111", "下载失败", e);
        }
    }

    /**
     * 上传Excel-徐玲博-2018-2-26 08:21:07
     * @param multipartFile 多媒体文件
     * @param request 请求
     * @param response 响应
     * @return 上传结果
     */
    @ResponseBody
    @RequestMapping(value = {"/importPersonExcel"}, method = RequestMethod.POST)
    public ItooResult importPersonExcel(@RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response ) {
        //excel对应实体
        List<PersonGradeModel> list;
        response.setContentType("uft-8");

        //region Excel解析成list
        try {
            String fileName = multipartFile.getOriginalFilename();//获得源文件名

            Map<Serializable, Serializable> map = new HashMap<>();
            map.put("sheetName", "互助网模板");  // sheet的名字
            map.put("Class", PersonGradeModel.class);
            list = ExcelUtil.importExcel(fileName, map, request, response);

            if (!CollectionUtils.isEmpty(list)) {
                int flag = personalInfoFacade.addListToPersonal(list);
                if(flag>0) {
                    return ItooResult.build(ResultCode.SUCCESS, "导入互助网成员成功");
                } else {
                    return ItooResult.build(ResultCode.FAIL, "导入互助网成员失败, 请检查所有成员信息或数据已导入！");
                }
            } else {
                return ItooResult.build(ResultCode.FAIL, "文件数据有无效值！");
            }
        } catch (Exception e) {
            logger.error("导入Excel操作]异常{}", e);
            return ItooResult.build(ResultCode.FAIL, "导入失败，请确认导入模板并检查数据正确性之后重新重试");
        }
    }

    //----------------------注册--------------------------------

    @ResponseBody
    @RequestMapping(value = {"/signIn"}, method = RequestMethod.POST)
    public ItooResult SignIn(@RequestBody UserModel userModel){
        boolean flag;
        try {
             flag= personalInfoFacade.insertUser(userModel);
            if(flag) {
                return ItooResult.build(ResultCode.SUCCESS, "注册互助网成员成功",flag);
            } else {
                return ItooResult.build(ResultCode.FAIL, "注册互助网成员失败 ！");
            }
        } catch (Exception e) {
            logger.error("注册异常{}", e);
            return ItooResult.build(ResultCode.FAIL, "注册互助网成员异常！");
        }
    }

    /**
     * 个人重置密码-袁甜梦-2018年3月20日15:09:30
     * @param userModel 用户实体
     * @return  是否更新成功
     */
    @ResponseBody
    @RequestMapping(value = {"/resetPassword"}, method = RequestMethod.POST)
    public ItooResult resetPassword(@RequestBody UserModel userModel){
        boolean flag;
        try {
            String userCode=userModel.getUserCode();
            flag= personalInfoFacade.resetPassword(userCode);
            if(flag) {
                return ItooResult.build(ResultCode.SUCCESS, "个人重置密码成功！",flag);
            } else {
                return ItooResult.build(ResultCode.FAIL, "个人重置密码失败 ！");
            }
        } catch (Exception e) {
            logger.error("重置密码异常{}", e);
            return ItooResult.build(ResultCode.FAIL, "个人重置密码异常！");
        }
    }
}
